package cn.jinbyte.core.helper;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.Map;

@Slf4j
@SuppressWarnings("unused")
public class SpringContextHelper implements ApplicationContextAware, BeanFactoryPostProcessor {
    @PostConstruct
    public void init() {
        log.info("加载组件{}", getClass().getSimpleName());
    }

    private static ApplicationContext applicationContext;

    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) {
        applicationContext = context;
    }

    @Override
    public void postProcessBeanFactory(@NonNull ConfigurableListableBeanFactory beanFactory) {
        SpringContextHelper.beanFactory = beanFactory;
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
        return applicationContext.getBean(name, clazz);
    }
    public static <T> Map<String, T> getBeans(Class<T> clazz) throws BeansException {
        return applicationContext.getBeansOfType(clazz);
    }

}